package org.handwerkszeug.tournament.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.handwerkszeug.tournament.Game;
import org.handwerkszeug.tournament.Player;

public class DefaultPlayer implements Player {

	protected String id;

	protected int matchpoint;

	protected Set<Player> played = new HashSet<Player>();

	protected List<Game> history = new ArrayList<Game>();

	public DefaultPlayer(String id) {
		super();
		assert id != null;
		this.id = id;
	}

	@Override
	public String id() {
		return this.id;
	}

	@Override
	public int matchpoint() {
		return this.matchpoint;
	}

	@Override
	public void receive(int point) {
		assert -1 < point;
		this.matchpoint += point;
	}

	@Override
	public Set<Player> played() {
		return Collections.unmodifiableSet(this.played);
	}

	@Override
	public void playWith(Game g) {
		assert g != null;
		this.history.add(g);
		for (Player p : g.players()) {
			if (this.equals(p) == false) {
				this.played.add(p);
			}
		}
	}

	@Override
	public List<Game> history() {
		return Collections.unmodifiableList(this.history);
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		result = prime * result + matchpoint;
		result = prime * result + ((played == null) ? 0 : played.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (getClass() != obj.getClass()) {
			return false;
		}
		DefaultPlayer other = (DefaultPlayer) obj;
		if (id == null) {
			if (other.id != null) {
				return false;
			}
		} else if (!id.equals(other.id)) {
			return false;
		}
		if (matchpoint != other.matchpoint) {
			return false;
		}
		if (played == null) {
			if (other.played != null) {
				return false;
			}
		} else if (!played.equals(other.played)) {
			return false;
		}
		return true;
	}

}
